<template>
  <div class="upate-profile">
    <img :src="img" alt="" ref="img">
    <!-- 底部标题 -->
    <van-nav-bar class="toolbar" left-text="取消" right-text="确定" @click-left="$emit('close')"
      @click-right="onClickRight" />
  </div>
</template>

<script>
import { updateUserPhoto } from '@/api/user'
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
export default {
  name: 'updateProfile',

  props: {
    // 选择后的图片对象
    file: {
      // type: [String, Object],
      required: true
    },
    // 选择前的图片地址
    value: {
      type: [String, Object],
      required: true
    }
  },

  data() {
    return {
      // 选择后的图片地址
      img: window.URL.createObjectURL(this.file),
      // 裁切器实例
      cropper: null
    }
  },

  mounted() {
    // 获取裁切器实例对象
    const image = this.$refs.img
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true
    })
    console.log(this.cropper)
  },

  methods: {
    // 裁切头像
    getCroppedCanvas() {
      return new Promise((resolve, reject) => {
        this.cropper.getCroppedCanvas().toBlob(file => {
          resolve(file)
        })
      })
    },
    // 修改头像
    async onClickRight() {
      // 如果接口要求 Content-Type 是 application/json
      // 则传递普通 JavaScript 对象
      // updateUserPhoto({
      //   photo: this.file
      // })

      // 如果接口要求 Content-Type 是 multipart/form-data
      // 则你必须传递 FormData 对象
      const files = await this.getCroppedCanvas()
      const formData = new FormData()
      formData.append('photo', files)

      await updateUserPhoto(formData)
      this.$toast.success('修改成功')
      this.$emit('close')
      // 通知父组件修改头像
      this.$emit('input', window.URL.createObjectURL(files))
    }
  }
}
</script>

<style lang="less" scope>
img {
  display: block;

  /* This rule is very important, please don't ignore this */
  max-width: 100%;
}

.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #000;
}
</style>
